package xyz.canran.project.algorithm.stack;

import java.util.Stack;

/**
 * 最小栈
 * 首先在保证正常入栈和出栈、获取栈顶元素功能基础上，增加O(1)时间复杂度的获取最小元素方法
 */
public class MinStack {

    private final Stack<Integer> dataStack;
    private final Stack<Integer> minStack;

    public MinStack() {
        dataStack = new Stack<>();
        minStack = new Stack<>();
    }

    public int push(int data) {
        int result = dataStack.push(data);
        if (minStack.isEmpty() || data < minStack.peek()) {
            minStack.push(data);
        }
        return result;
    }

    public int pop() {
        if (dataStack.isEmpty()) {
            return -1;
        }
        int temp = dataStack.pop();
        if (!minStack.isEmpty() && temp == minStack.peek()) {
            minStack.pop();
        }
        return temp;
    }

    public int top(){
        return dataStack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }

}
